package com.example.shop_front_api.utils;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;
import java.time.Instant;

public class Tool {

    //当前时间戳
    public static int getCurrentTime() {
        return (int) Instant.now().getEpochSecond();
    }

    //uuid生成
    public static UUID getUUID() {
        return UUID.randomUUID();
    }

    //手机号码格式检查
    public static Boolean isMobile(String mobile) {
        String mobileRule = "^1[3-9]\\d{9}$";
        return Pattern.matches(mobileRule, mobile);
    }

    //密码格式验证
    public static Boolean isValidPassword(String password) {
        String passwordRule = "^(?=.*[^\\d]).{8,}$";
        return Pattern.matches(passwordRule, password);
    }

    /**
     * 生成指定位数的随机数字（首位不为0）
     * @param digits 位数（正整数）
     * @return 随机数字
     */
    public static long generateRandomNumber(int digits) {
        if (digits <= 0) {
            throw new IllegalArgumentException("位数必须为正整数");
        }
        // 计算最小值（10^(digits-1)）和最大值（10^digits - 1）
        long min = (long) Math.pow(10, digits - 1);
        long max = (long) Math.pow(10, digits) - 1;
        // 生成 [min, max] 范围内的随机数
        Random random = new Random();
        return min + random.nextLong(max - min + 1);
    }

    //获取获取时间 年月日时分秒
    public static String getCurrentDate(String format) {
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return currentTime.format(formatter);
    }


    /**
     * 检查库存是否足够
     */
    public static boolean checkStock(Integer stock, Integer lockStock, Integer quantity) {
        if (stock == null || lockStock == null || quantity == null) {
            return false;
        }
        return (stock - lockStock) >= quantity;
    }

    /**
     * 获取可用库存
     */
    public static int getAvailableStock(Integer stock, Integer lockStock) {
        if (stock == null || lockStock == null) {
            return 0;
        }
        return stock - lockStock;
    }


}
